#include "server.h"
#include "connection.h"
#include "message_processor.h"

extern MessageProcessor message_processor; // 假设在其他地方定义了 MessageProcessor 实例

Server::Server(boost::asio::io_context& io_context, unsigned short port)
    : io_context_(io_context), acceptor_(io_context, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)) {
    start_accept();
    message_processor_ = &message_processor;
}

Server::~Server() = default;

void Server::start_accept() {
    auto new_connection = std::make_shared<Connection>(io_context_);
    acceptor_.async_accept(new_connection->socket(),
                           [this, new_connection](const boost::system::error_code& error) {
                               handle_accept(new_connection, error);
                           });
}

void Server::handle_accept(std::shared_ptr<Connection> new_connection, const boost::system::error_code& error) {
    if (!error) {
        connection_manager_.start(new_connection);
    }
    start_accept();
}

void Server::register_message_handler(uint32_t msg_type, std::function<void(const std::string&, std::shared_ptr<Connection>)> handler) {
    message_processor_->register_handler(msg_type, [handler](const google::protobuf::Message& msg, std::shared_ptr<Connection> connection) {
        std::string msg_str;
        msg.SerializeToString(&msg_str);
        handler(msg_str, connection);
    });
}

void Server::register_message_processor(MessageProcessor& processor) {
    message_processor_ = &processor;
}